<?php

namespace App\Jobs;

use App\Models\Crawler;
use App\Models\Position;
use App\Services\CrawlerService\driver\Xinxin21ccnnDriver;
use App\Services\TagService\TagService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class Viewer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $driver;
    public $url;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($driver,$url)
    {
        $this->driver=$driver;
        $this->url=$url;
    }

    /**
     * Execute the job.
     *
     * @param $driver
     * @param $url
     * @return bool
     */
    public function handle()
    {
        /** @var Xinxin21ccnnDriver $server */
        $md5=md5($this->url);
        $crawler=Crawler::whereMd5($md5)->first();
        if(!$crawler instanceof Crawler){
            $crawler=new Crawler();
            $crawler->url=$this->url;
            $crawler->md5=$md5;
            $crawler->save();
        }
        if($crawler->grabbed_at){
           return false;
        }
        $server = new $this->driver();
        $position_id=$server->getDetail($this->url)->save();
        $position=Position::find($position_id);
        $tag_service=new TagService();
        $tag_service->position($position);
        $crawler->grabbed_at=now();
        $crawler->save();
        return true;
    }
}
